<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <div>
            <el-input placeholder="请输入内容" v-model="userInfo.query" clearable @clear="getUsersList">
              <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="usersList" style="width: 100%" :stripe="true" :border="true">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <template v-slot:default="scope">
            <!-- scope.row获取该行对应的数据 -->
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot:default="scope">
            <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteMesBox(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" @click="showAllotRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="userInfo.pagenum"
        :page-sizes="[3, 5, 7, 10]" :page-size="userInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%" @close="resetForm">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--对话框按钮  -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改信息" :visible.sync="editDialogVisible" width="30%" @close="editDialogReset">
      <span>
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="allotRoleDialogVisible" width="30%" @close="setRoleDialogClosed">
      <div>
        <p>当前用户名：{{setRoleUser.username}}</p>
        <p>当前角色：{{setRoleUser.role_name}}</p>
        <p>
          分配新角色：
          <template>
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
              </el-option>
            </el-select>
          </template>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 定义邮箱验证规则
    const checkEmail = (rule, value, cb) => {
      const regEmail = /^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/
      if (regEmail.test(value)) {
        // 验证通过直接调用cb表明验证通过
        return cb()
      }
      // 验证不通过则给cb传一个Error对象
      cb(new Error('请输入合法的邮箱'))
    }
    // 定义手机号验证规则
    const checkMobile = (rule, value, cb) => {
      const regMobile = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 请求参数
      userInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 3
      },
      // 接收数据
      usersList: [],
      total: 1,
      // 添加用户对话框的显示与隐藏
      dialogVisible: false,
      // 修改用户信息对话框的显示与隐藏
      editDialogVisible: false,
      // 添加角色对话框
      allotRoleDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 接收用户修改信息
      editForm: {},
      // 添加表单的验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 需要分配角色的用户信息
      setRoleUser: {},
      // 角色列表
      rolesList: [],
      // 已选中的角色id值
      selectedRoleId: ''
    }
  },
  // 页面加载时调用
  created () {
    this.getUsersList()
  },
  methods: {
    // 获取用户列表
    async getUsersList () {
      const { data: res } = await this.$http.get('users', {
        params: this.userInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('用户列表获取失败')
      }
      // 接收数据
      this.usersList = res.data.users
      this.total = res.data.total
      console.log(this.usersList)
      console.log(this.total)
    },
    // 监听page-size改变的事件
    handleSizeChange (newSize) {
      // 将每页展示的条数赋值给pagesize
      this.userInfo.pagesize = newSize
      // 根据此pagesize重新获取数据
      this.getUsersList()
    },
    // 监听current-change改变
    handleCurrentChange (newPage) {
      // 将当前第几页赋值给pagenum
      this.userInfo.pagenum = newPage
      // 根据此pagenum重新请求
      this.getUsersList()
    },
    // switch按钮状态改变
    async userStateChange (scopeRow) {
      // 发送axios请求修改数据库中对应状态
      const { data: res } = await this.$http.put(
        `users/${scopeRow.id}/state/${scopeRow.mg_state}`
      )
      console.log(res)
      if (res.data.status !== 200) {
        // 失败则将switch状态重置回去
        scopeRow.mg_state = !scopeRow.mg_state
        this.$message.error('用户状态更新失败')
      }
      // 成功则将更改后的状态转化成布尔值并赋值给switch的值
      scopeRow.mg_state = !!res.data.mg_state
      this.$message.success('用户状态更新成功')
    },
    // 关闭添加用户对话框则重置表单
    resetForm () {
      this.$refs.addFormRef.resetFields()
    },
    // 表单预校验发起添加用户请求
    addUser () {
      // 获取表单引用对象
      this.$refs.addFormRef.validate(async (valid) => {
        // 验证未通过
        if (!valid) return
        // 通过验证，发起请求
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        // 隐藏对话框
        this.dialogVisible = false
        // 重新获取用户列表
        this.getUsersList()
      })
    },
    // 修改用户对话框
    async showEditDialog (id) {
      // 根据id查询对应信息
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      // 接收用户信息
      this.editForm = res.data
      // 弹出修改信息对话框
      this.editDialogVisible = true
    },
    // 编辑用户提交
    async editUser () {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 重新请求数据
        this.getUsersList()
        this.$message.success('用户信息修改成功')
      })
    },
    // 修改对话框关闭时重置表单
    editDialogReset () {
      this.$refs.editFormRef.resetFields()
    },
    // 删除用户时弹出确认消息
    async deleteMesBox (id) {
      const res = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '删除用户',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err) // catch捕获点击取消按钮，返回字符串cancel

      if (res !== 'confirm') {
        return this.$message('已取消删除')
      }
      const { data: para } = await this.$http.delete('users/' + id)
      if (para.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      // 重新请求数据
      this.getUsersList()
      this.$message.success('删除成功')
    },
    // 分配角色对话框
    async showAllotRoleDialog (scopeRow) {
      // 将当前用户信息存到data中
      this.setRoleUser = scopeRow
      console.log(this.setRoleUser)
      // 获取角色列表
      // 请求数据并接收
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      // 在data中接收数据
      this.rolesList = res.data
      console.log(this.rolesList)
      this.allotRoleDialogVisible = true
    },
    // 点击确定时分配角色
    async saveRoleInfo () {
      // 如果没有选择角色
      if (!this.selectedRoleId) {
        return this.$message.error('并未选择角色')
      }
      // console.log(this.setRoleUser.id)
      // console.log(this.selectedRoleId)
      // 发送分配角色请求
      const { data: res } = await this.$http.put(`users/${this.setRoleUser.id}/role`, {
        rid: this.selectedRoleId
      })
      console.log(res)
      if (res.meta.status === 400) {
        return this.$message.error('超级管理员不允许更改角色')
      }
      if (res.meta.status !== 400 && res.meta.status !== 200) {
        return this.$message.error('更新角色失败')
      }
      this.$message.success('更新角色成功')
      // 重新获取用户列表
      this.getUsersList()
      // 隐藏对话框
      this.allotRoleDialogVisible = false
    },
    // 角色对话框关闭时
    setRoleDialogClosed () {
      // 清空对话框中选中的角色
      this.selectedRoleId = ''
    }
  }
}
</script>

<style lang="less" scoped>
p{
  margin-bottom: 8px;
}
</style>
